package com.fare.taluo.application.impl.freight;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import antlr.StringUtils;

import com.fare.taluo.application.freight.FreightMonitorLowPriceForFlightApplication;
import com.fare.taluo.fetl.domain.entity.FreightMonitorCabinsEntity;
import com.fare.taluo.fetl.domain.entity.FreightMontiorEntity;
import com.fare.taluo.fusionCharts.FusionChartsTemplateModel;
import com.fare.taluo.fusionCharts.SimpleFusionChartsBuilder;
import com.fare.taluo.vo.fetl.FreightMonitorCabinsVO;
import com.fare.taluo.vo.fetl.FreightMonitorVO;
import com.foreveross.crawl.common.util.DateUtil;

@Transactional
@Scope("singleton")
@Service("freightMonitorLowPriceForFlightApplication")
public class FreightMonitorLowPriceForFlightApplicationImpl implements
		FreightMonitorLowPriceForFlightApplication {

	@Override
	public List<FreightMonitorVO> findFreightMonitorVOByTimeAndNO(String opDate, String flightDate,String flightNo,int size)throws Exception {
		List<FreightMonitorVO> listVO = new ArrayList<FreightMonitorVO>();
		FreightMontiorEntity freightMontiorEntity = new FreightMontiorEntity();
		List<FreightMontiorEntity> listEntity = new ArrayList<FreightMontiorEntity>();
		listEntity=freightMontiorEntity.findForLowPrice(opDate,flightDate, flightNo,size);
		if(listEntity !=null && listEntity.size()>0){
//			Collections.sort(listEntity, new Comparator<FreightMontiorEntity>() {
//				@Override
//				public int compare(FreightMontiorEntity o1,
//						FreightMontiorEntity o2) {
//					return 0;
//				}
//			});
			int showorderby = 1;
			String dateStr = null;
			Collections.reverse(listEntity); //将降序改为升序
			for(FreightMontiorEntity entity : listEntity){
				if(com.fare.taluo.util.StringUtils.isNotBlank(dateStr)
						&& dateStr.equals(DateUtil.formatDay(entity.getGrabDate(), "yyyy-MM-dd"))){
					showorderby++;
				}else{
					showorderby = 1;
				}
				dateStr = DateUtil.formatDay(entity.getGrabDate(), "yyyy-MM-dd");
					FreightMonitorVO vo =new FreightMonitorVO();
					vo.setId(entity.getId());
					vo.setGrabNum(showorderby);
					vo.setFlightNo(entity.getFlightNo());
					vo.setFlightDate(entity.getFlightDate());
					vo.setGrabDate(entity.getGrabDate());
					vo.setLowerPrice(entity.getLowerPrice());
					vo.setHigherPrice(entity.getHigherPrice());
					vo.setGrabChannelKey(entity.getGrabChannelKey());
					listVO.add(vo);
				
			}
		}
		return listVO;
	}

	@Override
	public List<FreightMonitorCabinsVO> findCabinEntityByFreightMonitor(String id) {
		List<FreightMonitorCabinsVO> listVO =new ArrayList<FreightMonitorCabinsVO>();
		FreightMonitorCabinsEntity freightMonitorCabinsEntity = new FreightMonitorCabinsEntity();
		List<FreightMonitorCabinsEntity> listEntity=new ArrayList<FreightMonitorCabinsEntity>();
		listEntity = freightMonitorCabinsEntity.findCabinEntityByFreightMonitor(id);
		if(listEntity !=null && listEntity.size()>0){
			for(FreightMonitorCabinsEntity entity :listEntity){
				FreightMonitorCabinsVO vo=new FreightMonitorCabinsVO();
				vo.setCabinName(entity.getCabinName());
				vo.setCabinType(entity.getCabinType());
				vo.setId(entity.getId());
				vo.setLevel(entity.getLevel());
				vo.setMonitorId(entity.getMonitorId());
				vo.setPrice(entity.getPrice());
				vo.setProductName(entity.getProductName());
				listVO.add(vo);
			}
		}
		return listVO;
	}

	@Override
	public String findXMLforFreightMonitor(List<FreightMonitorVO> list, int type)throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		double lowerPrice = 1000;
		double heightPrice =3000;
		FusionChartsTemplateModel model=FusionChartsTemplateModel.getNewDefaultInstance();//报表模型
		String lowerPriceStr=String.valueOf(lowerPrice);
		model.addChartAttr("yAxisMaxValue", "4000");
		model.addChartAttr("baseFont", "Arial");
		model.addChartAttr("baseFontSize", "12");
		model.addChartAttr("labelDisplay", "Rotate");
		model.addChartAttr("slantLabels", "1");
		//model.addChartAttr("bgColor", "111111");
		String tableName="舱位级别最低价";
		if(2==type){
			tableName ="子舱价格分布";
		}
		List<String> grabDate=new ArrayList<String>();//日期list
		grabDate.add("");//设置开头断点
		long dataSetId=1000L;
		if(list!=null && list.size()>0){
			FreightMonitorVO monitorVO =list.get(0);
			if("20006".equals(monitorVO.getGrabChannelKey())){
				type=1;
			}
			for(FreightMonitorVO vo :list){
				if(lowerPrice > vo.getLowerPrice() ){
					lowerPrice=vo.getLowerPrice()-100;
				}
				if(heightPrice < vo.getHigherPrice()){
					heightPrice = vo.getHigherPrice()+100;
				}
				String count ="";
				String grabDateStr= df.format(vo.getGrabDate());
				count+=grabDateStr.substring(8, 10)+"日第"+vo.getGrabNum()+"次";//XX日第X次
				grabDate.add(count);
			}
			grabDate.add("");//设置结尾断点
		
			model.addChartAttr(FusionChartsTemplateModel.AN_Caption, monitorVO.getFlightNo()+"航班"+df.format(monitorVO.getFlightDate()).substring(5, 10)+"日" +tableName );
			model.addCategroyLabels(grabDate);//X轴
			model.addChartAttr("yAxisMinValue", String.valueOf(lowerPrice));
			model.addChartAttr("yAxisMaxValue", String.valueOf(heightPrice));
			List<FreightMonitorCabinsVO>  lastCabins =new ArrayList<FreightMonitorCabinsVO>();
			lastCabins = findCabinEntityByFreightMonitor(monitorVO.getId());
			boolean isExit =false;
			List<String> labelList =new ArrayList<String>();
			List<String> labelName =new ArrayList<String>();
		//	List<FusionChartsTemplateModel> modelList = new ArrayList<FusionChartsTemplateModel>();
			
			for(FreightMonitorCabinsVO cvo:lastCabins){
				String setsStr ="<set/>";
				if(1==type){
					if(1==cvo.getLevel()){
						
						isExit=true;
						//String cur=findCabinEntityByType(monitorVO.getId(),cvo.getProductName());
						if(cvo.getPrice() !=null ){
							setsStr += "<set value='"+cvo.getPrice()+"' toolText=' 价格： ￥"+cvo.getPrice()+"  \n 时间： "+grabDate.get(1)+" \n 舱位： "+cvo.getProductName()+"'/>";
						}else{
							setsStr +="<set/>"; //如果该次航班没有此舱位，则设置断点
						}
						labelName.add(cvo.getProductName());
						labelList.add(setsStr);
					}
				}
				if(2==type){
					if(2==cvo.getLevel()){
						
						isExit=true;
						if(cvo.getProductName()==null || "网站专享".equals(cvo.getProductName())){
							//String cur = findCabinEntityByCabinName(monitorVO.getId(),cvo.getCabinName());
							if(cvo.getPrice() !=null){
								setsStr += "<set value='"+cvo.getPrice()+"' toolText=' 价格： ￥"+cvo.getPrice()+"  \n 时间： "+grabDate.get(1)+" \n 舱位： "+cvo.getCabinName()+" ' />";
							}else{
								setsStr +="<set/>"; //如果该次航班没有此舱位，则设置断点
							}
							labelName.add(cvo.getCabinName());
							labelList.add(setsStr);
					   }
					}
				}
				
			}
			int i=1;
			for(FreightMonitorVO mvo:list){
				
				if(1!=i){
					List<FreightMonitorCabinsVO>  cabins =findCabinEntityByFreightMonitor(mvo.getId());	
					List<String> newList =new ArrayList<String>();
					int j=0;
					for(String s:labelName){
						boolean labelisExit =false;
						if(1==type){
							for(FreightMonitorCabinsVO vo :cabins){
								if(vo.getLevel()==1 && s.equals(vo.getProductName())){
									String str=labelList.get(j)+"<set value='"+vo.getPrice()+"' toolText=' 价格： ￥"+vo.getPrice()+"  \n 时间： "+grabDate.get(i)+" \n 舱位： "+s+"'/>";
									newList.add(str);
									labelisExit=true;
									isExit=true;
									break;
								}
							}
							if(!labelisExit){
								String str=labelList.get(j)+"<set/>";
								newList.add(str);
							}
						}
						if(2==type){
							for(FreightMonitorCabinsVO vo :cabins){
								if(2==vo.getLevel() && s.equals(vo.getCabinName())){
									if(vo.getProductName()==null || "网站专享".equals(vo.getProductName())){
										String str=labelList.get(j)+"<set value='"+vo.getPrice()+"' toolText=' 价格： ￥"+vo.getPrice()+"  \n 时间： "+grabDate.get(i)+" \n 舱位： "+s+" ' />";
										newList.add(str);
										labelisExit=true;
										isExit=true;
										break;
									}
									
								}
							}
							if(!labelisExit){
								String str=labelList.get(j)+"<set/>";
								newList.add(str);
							}
						}
						j++;
					}
					for(FreightMonitorCabinsVO vo :cabins){
						if(1==type && 1==vo.getLevel()){
							boolean les =false;
								 for(String lab :labelName){ 
									 if(lab.equals(vo.getProductName())){
										 les=true; 
										 break;
									 }
								 }
							if(!les){
								String str="";
								for(int k=0;k<i;k++){
									str+="<set/>";
								}
								str +="<set value='"+vo.getPrice()+"' toolText=' 价格： ￥"+vo.getPrice()+"  \n 时间： "+grabDate.get(i)+" \n 舱位： "+vo.getProductName()+"'/>";
								newList.add(str);
								labelName.add(vo.getProductName());
							}
						 }
						if(2==type && 2==vo.getLevel() ){
							if(vo.getProductName()==null || "网站专享".equals(vo.getProductName())){
								boolean les =false;
								 for(String lab :labelName){ 
									 if(lab.equals(vo.getCabinName())){
										 les=true; 
										 break;
									 }
								 }
									if(!les){
										String str="";
										for(int k=0;k<i;k++){
											str+="<set/>";
										}
										str +="<set value='"+vo.getPrice()+"' toolText=' 价格： ￥"+vo.getPrice()+"  \n 时间： "+grabDate.get(i)+" \n 舱位： "+vo.getCabinName()+"'/>";
										newList.add(str);
										labelName.add(vo.getCabinName());
									}
							}
						}
					}
					labelList=newList;
				}
				i++;
			}
			for(int j=0 ;j<labelList.size();j++){
				String s=labelList.get(j);
				s+="<set/>";//设置结尾断点
				model.createDataSet(dataSetId);
				model.addDataSetAttr(dataSetId,FusionChartsTemplateModel.AN_Seriesname, labelName.get(j));
				model.addSetFullStrIntoDataSet(dataSetId, s);
				model.addDataSetAttr(dataSetId, FusionChartsTemplateModel.AN_RenderAs, "Line");//以折现展示数据
				dataSetId++;
				
			}
			
		//	List<FreightMonitorCabinsVO>  cabins=findCabinEntityByFreightMonitor(monitorVO.getId());
			
			/*for(FreightMonitorCabinsVO cvo:cabins){
				int i=1;
				if(1==type){
					if(1==cvo.getLevel()){
						isExit=true;
						model.createDataSet(dataSetId);
						model.addDataSetAttr(dataSetId,FusionChartsTemplateModel.AN_Seriesname, cvo.getProductName());
						//List<String> sets =new ArrayList<String>();
						String setsStr ="<set/>"; //设置开头断点
						for(FreightMonitorVO vo :list){
						
							String cur=findCabinEntityByType(vo.getId(),cvo.getProductName());
							if(cur !=null){
								setsStr += "<set value='"+cur+"' toolText=' 价格： ￥"+cur+"  \n 时间： "+grabDate.get(i)+" \n 舱位： "+cvo.getProductName()+"'/>";
							}else{
								setsStr +="<set/>"; //如果该次航班没有此舱位，则设置断点
							}
							
						}
						 
						// setsStr +=FusionChartsUtil_2.generateDashedByFormat(sets);//完整的Set字符串
						 setsStr +="<set/>";//设置结尾断点
						 model.addSetFullStrIntoDataSet(dataSetId, setsStr);
						 model.addDataSetAttr(dataSetId, FusionChartsTemplateModel.AN_RenderAs, "Line");//以折现展示数据
						 dataSetId++;
					}
				}else if(2==type){
							if(2==cvo.getLevel()){
							isExit=true;
							model.createDataSet(dataSetId);
							model.addDataSetAttr(dataSetId,FusionChartsTemplateModel.AN_Seriesname, cvo.getCabinName());
							//List<String> sets =new ArrayList<String>();
							String setsStr ="<set/>";//设置开头断点
							for(FreightMonitorVO vo :list){
									String cur = findCabinEntityByCabinName(vo.getId(),cvo.getCabinName());
									if(cur !=null){
										setsStr += "<set value='"+cur+"' toolText=' 价格： ￥"+cur+"  \n 时间： "+grabDate.get(i)+" \n 舱位： "+cvo.getCabinName()+" ' />";
									}else{
										setsStr +="<set/>"; //如果该次航班没有此舱位，则设置断点
									}
							}
							 
							// setsStr +=FusionChartsUtil_2.generateDashedByFormat(sets);//完整的Set字符串
							 setsStr +="<set/>";//设置结尾断点
							 model.addSetFullStrIntoDataSet(dataSetId, setsStr);
							 model.addDataSetAttr(dataSetId, FusionChartsTemplateModel.AN_RenderAs, "Line");//以折现展示数据
							 dataSetId++;
							}
				}
				i++;
			}*/
			if(!isExit){//返回空报表
				String setsStr ="<set/>"; 
				model.createDataSet(dataSetId);
				model.addDataSetAttr(dataSetId,FusionChartsTemplateModel.AN_Seriesname, "");
				model.addSetFullStrIntoDataSet(dataSetId, setsStr);
				model.addDataSetAttr(dataSetId, FusionChartsTemplateModel.AN_RenderAs, "Line");//以折现展示数据
				dataSetId++;
			}
			// model.addStyleToObject("ToolTip", FusionChartsTemplateModel.STYLE_ToolTip_FontSize_15);//全局style
			// model.addStyleToObject("Caption", FusionChartsTemplateModel.STYLE_Caption_FontSize_15);//全局style,标题15
			 String xml=SimpleFusionChartsBuilder.getInstance().buildXMLStr(model);
			 return xml;
			
		}else{//如果为空返回空报表
			model.addChartAttr("yAxisMinValue", lowerPriceStr);
			model.addChartAttr(FusionChartsTemplateModel.AN_Caption, tableName);//标题
			model.addCategroyLabels(grabDate);//X轴
			String setsStr ="<set/>"; 
			model.createDataSet(dataSetId);
			model.addDataSetAttr(dataSetId,FusionChartsTemplateModel.AN_Seriesname, "");
			model.addSetFullStrIntoDataSet(dataSetId, setsStr);
			model.addDataSetAttr(dataSetId, FusionChartsTemplateModel.AN_RenderAs, "Line");//以折现展示数据
			dataSetId++;
			//model.addStyleToObject("ToolTip", FusionChartsTemplateModel.STYLE_ToolTip_FontSize_15);//全局style
			//model.addStyleToObject("Caption", FusionChartsTemplateModel.STYLE_Caption_FontSize_15);//全局style,标题15
			String xml=SimpleFusionChartsBuilder.getInstance().buildXMLStr(model);
			return xml;
		}
	}
	
	/**
	 * 根据航班ID，舱位类型 获得价格
	 * @param monitorId 航班ID
	 * @param cabinType 舱位类型（头等舱 经济舱什么的）
	 * @return
	 */
	public String findCabinEntityByType(String monitorId,String cabinType){
		List<FreightMonitorCabinsVO> list=findCabinEntityByFreightMonitor(monitorId);
		for(FreightMonitorCabinsVO vo :list){
			if(1==vo.getLevel() && cabinType.equals(vo.getProductName())){
				return vo.getPrice();
			}
		}
		return null;
		
	}
	
	/**
	 * 根据航班ID，仓位名称（子舱） 舱位类型 来获得价格
	 * @param monitorId 航班ID
	 * @param cabinName仓位名称（子舱）
	 * @param cabinType 舱位类型（头等舱 经济舱什么的）
	 * @return
	 */
	public String findCabinEntityByCabinName(String monitorId,String cabinName){
		List<FreightMonitorCabinsVO> list=findCabinEntityByFreightMonitor(monitorId);
		for(FreightMonitorCabinsVO vo :list){
			if(vo.getProductName()==null){
				if(2==vo.getLevel() && cabinName.equals(vo.getCabinName())){
					return vo.getPrice();
				}
			}else {
				if(2==vo.getLevel() && cabinName.equals(vo.getCabinName()) && vo.getProductName().equals("网站专享")){
					return vo.getPrice();
				}
			}
		}
		return null;
		
	}

}
